package com.yby6.tencentaigc.utils;

import cn.hutool.core.bean.BeanUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tts.v20190823.TtsClient;
import com.tencentcloudapi.tts.v20190823.models.TextToVoiceRequest;
import com.tencentcloudapi.tts.v20190823.models.TextToVoiceResponse;
import com.yby6.tencentaigc.config.TencentConfig;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 腾讯云语音合成
 *
 * @author Yang Shuai
 * Create By 2023/12/21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TencentUtils {
    private static TencentUtils tencentUtils;
    private final TencentConfig tencentConfig;

    /**
     * 要在静态方法里面调用IOC容器的bean对象
     * PostConstruct 在构造函数执行之后执行。
     * 可以方便的把注入的bean对象给到静态属性
     * 源码： AutowiredAnnotationBeanPostProcessor 的 buildAutowiringMetadata 函数
     * isStatic 绕过了静态不进行注入
     */
    @PostConstruct
    public void postConstruct() {
        tencentUtils = this;
    }

    /**
     * 文本转语音
     *
     * @param request 参数
     * @return {@link String}
     */
    public static String textToVoice(TextToVoiceRequest request) {
        Credential cred = new Credential(tencentUtils.tencentConfig.getSecretId(), tencentUtils.tencentConfig.getSecretKey());
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("tts.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        TtsClient client = new TtsClient(cred, "ap-shanghai", clientProfile);
        TextToVoiceRequest req = new TextToVoiceRequest();
        BeanUtil.copyProperties(request, req);
//        req.setText("你好呀 杨不易");
//        req.setSessionId("123456798");
//        req.setVoiceType(301032L);
//        req.setCodec("mp3");
//        req.setEmotionCategory("happy");
        // 返回的resp是一个TextToVoiceResponse的实例，与请求对象对应
        TextToVoiceResponse resp = null;
        try {
            resp = client.TextToVoice(req);
            log.info("rep:{}", resp.getRequestId());
        } catch (TencentCloudSDKException e) {
            log.error("【腾讯云语音合成接口调用异常】", e);
            throw new RuntimeException(e);
        }

        return "data:audio/mp3;base64," + resp.getAudio();
    }


}
